package org.example.springbootserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.example.springbootserver.dao.UserDao;
import org.example.springbootserver.pojo.R;
import org.example.springbootserver.pojo.User;
import org.example.springbootserver.service.UserService;
import org.example.springbootserver.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final PasswordEncoder passwordEncoder;

    @Autowired
    private UserDao userDao;
    private final EmailUtil emailUtil;

    @Override
    public R Login(User loginArgs) {
        Map <String, Object>resultMap=new HashMap<>();
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getEmail,loginArgs.getEmail());
        User user=userDao.selectOne(lambdaQueryWrapper);
        if(user==null)
            return R.error("该账号不存在");
        if(passwordEncoder.matches(loginArgs.getPassword(),user.getPassword()))
            return R.success(null);
        return R.error("密码错误");
    }

    @Override
    public R Register(User user,String verification) {
        if (emailUtil.verificationEmailCode(user.getEmail(),verification)) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userDao.insert(user);
            return R.success(null);
        }
        else
            return R.error("验证码错误");
    }

}
